import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/data/entities/home/risk_tree_entity.dart';
import 'package:safetymonitor/generated/assets.dart';
import 'package:safetymonitor/modules/home/home_page/home_page_view.dart';
import 'package:safetymonitor/modules/home/user/user_view.dart';
import 'package:safetymonitor/router/app_pages.dart';

class HomeController extends GetxController
    with GetSingleTickerProviderStateMixin {
  var index = 0.obs;

  final myTabs = <Widget>[
    HomePagePage(),
    UserPage(),
  ];

  final tabName = ['首页', '个人中心'];

  final tabIcon = [Assets.svgTabHomeSelected, Assets.svgTabMineSelected];

  final tabCancel = [
    Assets.svgTabHomeCancel,
    Assets.svgTabMineCancel,
  ];

  /// 上一次点击返回的时间
  DateTime lastBackPressTime = DateTime.now();

  /// WillPopScope退出判断
  bool exitReminder() {
    if (DateTime.now().difference(lastBackPressTime) >
        const Duration(seconds: 2)) {
      AppToast.showWarning('再次点击退出');
      lastBackPressTime = DateTime.now();
      return false;
    } else {
      return true;
    }
  }

  /// 判断是否有升级
  // void checkUpdate() async {
  //   final res = await AuthApis.appUpdate().execute();
  //   res.onSuccess((value) {
  //     if (value.data != null) {
  //       if (isUpdateVersion(value.data!.version, Global.packageInfo.version)) {
  //         // 有升级
  //         showDialog(
  //           barrierDismissible: false,
  //           context: Get.context!,
  //           builder: (context) {
  //           return WillPopScope(
  //             onWillPop: () async => false,
  //             child: UpdateDialog(
  //               downloadAddress: value.data!.downloadAddress ?? '',
  //               isForce: value.data!.isForcedUpgrade == 1,
  //               upDateContent: value.data!.upgradeDescription ?? '',
  //               version: value.data!.version ?? '',
  //             ),
  //           );
  //         },);
  //       }
  //     }
  //   });
  // }

  /// 判断当前版本号和后台版本号是否一致
  /// [newVersion] 后台版本号
  /// [old] 当前版本号
  /// return true 需要升级 false 不需要升级
  bool isUpdateVersion(String? newVersion, String? old) {
    if (newVersion == null ||
        newVersion.isEmpty ||
        old == null ||
        old.isEmpty) {
      return false;
    }
    int newVersionInt, oldVersion;
    final newList = newVersion.split('.');
    final oldList = old.split('.');
    if (newList.isEmpty || oldList.isEmpty) {
      return false;
    }
    for (int i = 0; i < newList.length; i++) {
      newVersionInt = int.parse(newList[i]);
      oldVersion = int.parse(oldList[i]);
      if (newVersionInt > oldVersion) {
        return true;
      } else if (newVersionInt < oldVersion) {
        return false;
      }
    }
    return false;
  }

  // 关闭页面
  closePage() {
    /// 返回带参
    Get.back();
  }

  /// 跳转隐患整改
  void jumpToSnap() {
    // 随手拍重构
    // Get.toNamed(Routes.snapShot);
    Get.toNamed(Routes.snapShotDanger);
  }

  List<RiskTreeEntity> treeList = [];

  @override
  void onInit() {
    super.onInit();
    _getCompanyTreeTree();
  }

  void _getCompanyTreeTree() async {
    final res = await HttpUtil()
        .generateGetRequest<List<RiskTreeEntity>>(Interface.companyTree)
        .execute(isShowToast: false);
    res.onSuccess((result) {
      if (result.data != null) {
        treeList = result.data!;
        traverseAndAssignUniqueId(treeList);
      }
    });
  }
  int uniqueIdCounter = 0;
  void traverseAndAssignUniqueId(List<RiskTreeEntity> nodes) {
    for (var node in nodes) {
      // 为当前节点赋一个唯一数值
      node.id = uniqueIdCounter++;
      // 如果有子节点，递归赋值
      if (node.children != null && node.children!.isNotEmpty) {
        traverseAndAssignUniqueId(node.children!);
      }
    }
  }
}
